package org.showminifier.servlet;

import java.io.IOException;

import javax.jdo.JDOObjectNotFoundException;
import javax.jdo.PersistenceManager;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.showminifier.core.Options;
import org.showminifier.web.PMF;
import org.showminifier.web.Settings;
import org.showminifier.web.Util;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

/**
*
* Show Minifier
* Author: Shihua Ma <beijing.josh@gmail.com>
* Copyright (c) 2010 Shihua Ma
* Licensed under the MIT license.
*
*/

@SuppressWarnings("serial")
public class SettingsServlet extends HttpServlet{

	public void doGet(HttpServletRequest req, HttpServletResponse resp)
	throws IOException, ServletException{
		UserService userService = UserServiceFactory.getUserService();
        User user = userService.getCurrentUser();
        if(user == null){
        	req.setAttribute("errors","Your are not sign in.");
        	RequestDispatcher dispatcher =
      	      req.getRequestDispatcher("error.jsp");
    			dispatcher.forward(req, resp);
        	return;
        }
        RequestDispatcher dispatcher =
    	      req.getRequestDispatcher("settings.jsp");
  			dispatcher.forward(req, resp);
    }
	
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
	throws IOException, ServletException{
		UserService userService = UserServiceFactory.getUserService();
        User user = userService.getCurrentUser();
		String message = "";
        if(user == null){
        	resp.setStatus(HttpServletResponse.SC_FORBIDDEN);
        }
        
        Key key = Util.getKeyForSetting(user);
        Options options = Util.buildOptions(req, false);
        
        PersistenceManager pm = PMF.get().getPersistenceManager();
        Settings settings = null;
        try{
        	settings = pm.getObjectById(Settings.class,key);
        }catch(JDOObjectNotFoundException e){
			resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
			return;
		}
		if(settings == null){
			settings = new Settings();
			settings.setKey(key);
			settings.setOptions(options);
			settings.setUser(user);
			message = "Your settings is saved.";
		}else{
			settings.setOptions(options);
			message = "Your settings is updated.";
		}
		pm.makePersistent(settings);
		req.setAttribute("message",message);
		pm.close();
		RequestDispatcher dispatcher =
  	      req.getRequestDispatcher("settings.jsp");
			dispatcher.forward(req, resp);
	}
}
